/* eslint-disable no-param-reassign */
import { useStore } from '@/hooks';
import TauTable from '@/components/TauTable';
import UploadPanel from '@/components/UploadPanel';
import { Button, Dialog, Form, ResponsiveGrid, Icon, Upload } from '@alifd/next';
import React, { useEffect, useRef, useState } from 'react';
import { t } from '@lingui/macro';
import DrawerFooter from '@/components/DrawerFooter';
import { FieldsGrid, TitleGrid, companyModal, column } from '../stores/definitions';
import { observer } from 'mobx-react-lite';
import { observable, toJS } from 'mobx';
import AttachmentForm from './AttachmentForm';
import moment from 'moment';
import styles from './DataForm.module.scss';

const { Cell } = ResponsiveGrid;

const FromItem = Form.Item;

const DataForm = ({ modal, companyId, onCancel, onSubmit, handleCustomRequest }) => {
  const { companyStore: store } = useStore();
  // 使用useRef进行拼接字段且不会造成重绘
  const editCtx = useRef({ origin: {}, changed: {} }).current; // 用于计算是否修改
  const [isViewMode] = useState(modal[0] === 'check');
  const formProps = isViewMode ? { field: false } : {};
  const [company] = useState(() => observable({}));
  const [disabledAdd, setDisabledAdd] = useState(false);
  const uploaderRef = useRef();
  useEffect(() => { if (modal[1]?.startsWith?.('toClose')) handleCancel(); }, [modal]);

  useEffect(() => {
    if (companyId) {
      (async () => {
        const data = await store.get(companyId);
        if (data?.logo && JSON.stringify(data.logo) !== '[]') {
          setDisabledAdd(true);
        }
        editCtx.origin = _.cloneDeep(data);
        _.assign(company, { ...data });
      })();
    } else {
      // 添加时给初始值
      _.set(company, 'singleDriver', false);
    }
  }, []);

  if (!company) return <></>;

  const overrideModel = {
    logo: {
      label: t`公司LOGO`,
      ui: {
        renderer: (r) => {
          const img = r?.map((item) => {
            if (item.originFileObj) {
              return item;
            }
            return ({
              uid: item.uid,
              state: 'done',
              name: item.title,
              type: item.type,
              url: `${API_BASE}/api/files/${item.uid}`,
              downloadURL: `${API_BASE}/api/files/${item.uid}`,
              imgURL: `${API_BASE}/api/files/${item.uid}?${moment()}`,
            });
          });
          return (
            <Upload.Card
              listType="card"
              className={disabledAdd ? styles.disabled_add : styles.container}
              value={img}
              name="logo"
              beforeUpload={beforeUpload}
              headers={{ Authorization: `Bearer ${TOKEN}` }}
              data={(file) => {
                return { binaryId: file.uid, mimeType: file.type };
              }}
              autoUpload={false}
              ref={saveUploaderRef}
              onPreview={handlePreview}
              formatter={(res, files) => {
                return {
                  uid: files.uid,
                  name: files.name,
                  state: 'done',
                  type: files.type,
                  url: `${API_BASE}/api/files/${files.uid}`,
                  downloadURL: `${API_BASE}/api/files/${files.uid}`,
                  imgURL: `${API_BASE}/api/files/${files.uid}`,
                };
              }}
              request={customRequest}
              onChange={handleUploadAdd}
              useDataURL
              action={`${API_BASE}/upload`}
              accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp, image/webp"
            />
          );
        },
      },
    },
  };

  /**
   * @description 动态回现表单数据
   * @param {*} values
   * @param {*} item 数据Items
   */
  const handleChange = (values, item) => {
    const { name, value } = item;
    _.set(company, name, value);
    // 联动效果可以在这里通过设置channel属性实现
    if (name === 'independentAccount.collectionAccountInformation.type') {
      _.unset(company, 'independentAccount.collectionAccountInformation.name');
      _.unset(company, 'independentAccount.collectionAccountInformation.accountIdentification');
    }
    // eslint-disable-next-line eqeqeq
    editCtx.changed[name] = value == _.get(editCtx.origin, name) ? undefined : value;
  };


  const saveUploaderRef = (ref) => {
    if (ref) uploaderRef.current = ref.getInstance();
  };

  const beforeUpload = (info, options) => {
    return options;
  };

  const customRequest = (data) => {
    handleCustomRequest(data);
  };

  /**
  * @description 上传组件事件
  * @param {*} v
  */
  const handleUploadAdd = (v) => {
    if (v?.length >= 1) {
      _.set(company, 'logo', v);
      setDisabledAdd(true);
    } else {
      setDisabledAdd(false);
    }
  };

  const handlePreview = ({ url }) => {
    Dialog.show({
      title: t`预览`,
      content: <img src={url} style={{ maxWidth: '800px', width: '100%', height: '100%', objectFit: 'cover' }} />,
      footer: false,
    });
  };

  /**
   * @description 提交表单实现修改车辆
   * @param {*} r formData
   */
  const handleSubmit = (values, errors) => {
    if (!_.isEmpty(errors)) {
      console.log('🚀 _ file: DataForm.jsx:162 _ errors:', errors);
      return;
    }
    const { dateOfIncorporate, logo = [] } = company;
    const data = {
      ...company,
      dateOfIncorporate: moment.utc(dateOfIncorporate).toISOString(),
    };
    let toggleImg = [];
    if (JSON.stringify(logo) !== '[]') {
      toggleImg = logo?.map((item) => ({
        title: item.name,
        uid: company?.id,
        type: item.type,
      }));
    }
    onSubmit?.({ ...data, logo: toggleImg });
    uploaderRef.current && uploaderRef.current.startUpload();
  };
  const handleCancel = () => {
    // eslint-disable-next-line no-return-assign
    if (!_.isEmpty(_.transform(editCtx.changed, (r, v, k) => v !== undefined && (r[k] = v)))) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => onCancel?.(),
      });
      return;
    }
    onCancel?.();
  };

  return (
    <Form
      inline
      isPreview={isViewMode}
      {...formProps}
      value={company}
      onChange={handleChange}
      useLabelForErrorMessage
    >
      <TitleGrid title={t`公司信息`} />
      <FieldsGrid
        formData={company}
        mode={modal[0]}
        overrideModel={overrideModel}
        fields={['name', 'registerAddr', 'tel', 'address', 'orgCode', 'dateOfIncorporate', 'status', 'operating', 'singleDriver', 'logo']}
      />
      <TitleGrid title={t`分账信息`} />
      <FieldsGrid
        formData={company}
        mode={modal[0]}
        fields={['mchId', 'independentAccount.period']}
      />
      <TitleGrid title={t`负责人信息`} />
      <FieldsGrid
        formData={company}
        mode={modal[0]}
        fields={['orgDirector', 'directorIdType', 'directorId', 'directorTel']}
      />
      <AttachmentPanel company={company} mode={modal[0]} />

      <DrawerFooter>
        <FromItem>
          {!isViewMode && <Form.Submit validate type="primary" onClick={handleSubmit}>{t`保存`}</Form.Submit>}
          <Button style={{ marginLeft: 8 }} onClick={handleCancel}>{t`取消`}</Button>
        </FromItem>
      </DrawerFooter>

    </Form>
  );
};
const AttachmentPanel = observer(({ company, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'check';

  useEffect(() => {
    if (company?.attachments?.length) setIdx(0);
  }, [company.attachments]);

  const handleAddAttachment = () => {
    if (!company?.attachments) company.attachments = [];
    company.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(company.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    company.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid title={<span>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={7}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(company?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, companyModal.attachments[0]),
              column('description', {}, companyModal.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`company:${company.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(company.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              company.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              company.attachments[idx]?.binaryId.splice(company.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(company.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default observer(DataForm);
